package com.example.rabbitmqdemo.listener;

import com.example.rabbitmqdemo.constant.Constants;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: hp
 * Date: 2025-04-03
 * Time: 9:26
 */
@Component
public class QosListener {
    @RabbitListener(queues = Constants.QOS_QUEUE)
    public void handleMessage(Message message, Channel channel) throws IOException {
        try {
            System.out.printf("111接收到消息: %s , deliveryTag: %d \n",new String(message.getBody(),"UTF-8"),message.getMessageProperties().getDeliveryTag());
            //模拟业务处理的时间
            Thread.sleep(2000);

            //确认消息(肯定)
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);

        }catch (Exception e) {
            //否定确认
            //最后一个参数为true，则发生异常重新入队，false，为不再入队
            channel.basicNack(message.getMessageProperties().getDeliveryTag(),false,true);
        }
    }

    @RabbitListener(queues = Constants.QOS_QUEUE)
    public void handleMessage2(Message message, Channel channel) throws IOException {
        try {
            System.out.printf("222接收到消息: %s , deliveryTag: %d \n",new String(message.getBody(),"UTF-8"),message.getMessageProperties().getDeliveryTag());
            //模拟业务处理的时间
            Thread.sleep(1000);
            //确认消息(肯定)
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);

        }catch (Exception e) {
            //否定确认
            //最后一个参数为true，则发生异常重新入队，false，为不再入队
            channel.basicNack(message.getMessageProperties().getDeliveryTag(),false,true);
        }
    }


}
